import { STORAGE_TOKEN_KEY } from '@/stores/mutation-type'
import { useLocalStorage } from '@vueuse/core'

const token = useLocalStorage(STORAGE_TOKEN_KEY, '')
const STORAGE_TOKEN_EXPIRE_AT = 'access_token_expire_at'

function getExpireAt(): number {
  const raw = localStorage.getItem(STORAGE_TOKEN_EXPIRE_AT)
  if (!raw) return 0
  const n = Number(raw)
  return Number.isFinite(n) ? n : 0
}

function getConfigTTLHours(): number {
  try {
    const saved = localStorage.getItem('APP_CONFIG')
    if (saved) {
      const cfg = JSON.parse(saved)
      const v = Number(cfg?.SESSION_TTL_HOURS)
      if (Number.isFinite(v) && v > 0) return v
    }
  } catch {}
  try {
    const v = Number((window as any).APP_CONFIG?.SESSION_TTL_HOURS)
    if (Number.isFinite(v) && v > 0) return v
  } catch {}
  return 12 // 默认半天
}

function isLogin() {
  const t = token.value
  if (!t) return false
  const expireAt = getExpireAt()
  if (!expireAt) return true
  return Date.now() < expireAt
}

function getToken() {
  return token.value
}

function setToken(newToken: string) {
  token.value = newToken
}

function setTokenWithTTL(newToken: string, ttlHours?: number) {
  setToken(newToken)
  const hours = Number.isFinite(ttlHours as number) && (ttlHours as number)! > 0 ? (ttlHours as number) : getConfigTTLHours()
  const expireAt = Date.now() + hours * 60 * 60 * 1000
  localStorage.setItem(STORAGE_TOKEN_EXPIRE_AT, String(expireAt))
}

function clearToken() {
  token.value = null
  localStorage.removeItem(STORAGE_TOKEN_EXPIRE_AT)
}

export { isLogin, getToken, setToken, setTokenWithTTL, clearToken, getConfigTTLHours }
